package crp.core.portal.domain.services;

import crp.core.portal.domain.messages.PortalMessages;
import crp.core.portal.domain.models.PortalSectionConfig;
import crp.core.portal.domain.models.PortalSectionEntity;
import crp.core.portal.domain.repositories.PortalSectionRepository;
import crp.core.shared.LifecycleStatus;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class PortalSectionEditor {
    private final PortalSectionRepository portalSectionRepository;

    @Inject
    public PortalSectionEditor(PortalSectionRepository portalSectionRepository) {
        this.portalSectionRepository = portalSectionRepository;
    }

    public PortalSectionEntity create(String name, PortalSectionConfig config) {
        PortalSectionEntity entity = new PortalSectionEntity();
        entity.setName(name);
        entity.setOrderNumber(portalSectionRepository.nextOrderNumber());
        entity.setConfig(config);
        entity.setStatus(LifecycleStatus.ENABLED);
        portalSectionRepository.persist(entity);
        return entity;
    }

    public boolean deleteById(String id) {
        return portalSectionRepository.deleteById(id);
    }

    public PortalSectionEntity update(String id, String name, PortalSectionConfig config) {
        return portalSectionRepository.findByIdOptional(id)
                .map(section -> {
                    section.setName(name);
                    section.setConfig(config);
                    portalSectionRepository.persist(section);
                    return section;
                })
                .orElseThrow(() -> PortalMessages.INSTANCE.sectionNotFound(id));
    }
}
